

#include <iostream>
#include <cstdlib>
#include "Router.h"
#include "logger.h"

using namespace std;

CLogger m_oLogger;
Communicator oCommunicator;

// Thread function to receive data
static void* Interface(void* param);

int main(int argc, char* argv[])
{

	int nRouterID;
	char cFilename[20] = "Log";

	if (argc != 2)
	{
		printf("Usage: %s <RouterID>\n", argv[0]);
		exit(0);
	}
	else
	{
		nRouterID = atoi(argv[1]);
		if(nRouterID == 0)
		{
			cout<<"Incorrect RouterID!!!"<<endl<<"Usage: "<<argv[0]<<" <RouterID>\n"<<endl;
			return 0;
		}
	}
	sprintf(cFilename, "log/log_%d.txt", nRouterID);
	m_oLogger.InitLogging(5,cFilename,1000);
	m_oLogger.log(1,"*************Starting Application******************");

	pthread_attr_init(&attrInterface);

	ConfigReader initObj;
	NODE_INFO nodeInfo;
	vector<NEIGBOUR_INFO> vecNeigbInfo;
	initObj.Initialize(nodeInfo, vecNeigbInfo, nRouterID);


	oCommunicator.Initialize(nodeInfo,vecNeigbInfo, &m_oLogger);
	oCommunicator.StartCommunicator();

	pthread_create(&tidInterface, &attrInterface, Interface, NULL);

	pthread_join(tidInterface, NULL);
}


static void* Interface(void* param)
{
	string strUserInput;
	int destRouterID;
	while(1)
	{
		printf("Command->");
		getline(cin, strUserInput);
		if(strUserInput.compare("rt") == 0)
		{
			oCommunicator.printRoutingTable();
		}
		else if(strUserInput.compare("exit") == 0)
		{
			cout<<"EXITING!!"<<endl;
			pthread_exit(0);
		}
		else
		{
			char *tempStr = (char *)strUserInput.c_str();
			if(tempStr[0] == '\0')
			{
				continue;
			}
			tempStr = NULL;
			tempStr = strtok((char *)strUserInput.c_str(), " \t");
			if(tempStr == NULL)
			{
				printf("Wrong Command\r\n");
				continue;
			}
			if(strcmp(tempStr, "sd") == 0)
			{
				tempStr = strtok(NULL, " \t");
				destRouterID = atoi(tempStr);
				tempStr = strtok(NULL, " \t");
				printf("Router ID: %d \r\nMessage: %s\r\n", destRouterID, tempStr);
				oCommunicator.SendData(destRouterID, tempStr, strlen(tempStr));
			}
			else
			{
				printf("Wrong Command\r\n");
			}
		}
	}
}
